﻿$(function () {
	var $win = $(window),
		$doc = $(document),
		isLoaded = true,
		$list = $('#list'),
		page = 0,
		$icon = $('.uk-icon-spinner').parent(),
		token = document.getElementsByName('__RequestVerificationToken')[0].value,
		rootUrl = window.location.protocol + '//' + window.location.host + '/',
		template =
			'<li class="uk-text-center pic-item opacity-fadein">' +
			'<a class="uk-thumbnail" href="{url}">' +
			'<img src="{picUrl}" alt="{word}" title="{word}">' +
			'<div class="uk-thumbnail-caption">{painter} <span class="uk-text-bold">{word}</span></div>' +
			'</a>' +
			'</li>';

	function getHtml(i) {
		return template
			.replace(/{url}/g, rootUrl + i.Id)
			.replace(/{picUrl}/g, i.PictureUrl)
			.replace(/{word}/g, i.Word)
			.replace(/{painter}/g, i.Painter);
	}

	function preloadImages(array, callback) {
		var i = array.length,
			j = i;

		while (i--) {
			var img = new Image();
			img.onload = onload;
			img.src = array[i].PictureUrl;
		}

		function onload(){
			j--;
			j === 0 && callback();
		}
	}

	$win.scroll(function () {
		if (isLoaded && $win.scrollTop() >= $doc.height() - $win.height() - 10) {
			isLoaded = false;
			page++;
			$icon.css('opacity', 1);
			Ajax.post({
				url: '/loadFeed',
				data: {
					page: page,
					__RequestVerificationToken: token
				},
				json: true,
				done: function (data) {
					if (data.length == 0) {
						$win.unbind('scroll');
						$icon.css('opacity', 0);
					} else {
						preloadImages(data, function () {
							var append = '', n = data.length;

							while (n--) append = getHtml(data[n]) + append;

							$list.append(append);

							isLoaded = true;

							$icon.css('opacity', 0);
						});
					}
				}
			});
		}
	});

	if (isLoaded && $win.scrollTop() >= $doc.height() - $win.height() - 10) {
		$win.trigger('scroll');
	}
});